from core.exception.errors import ValidateError
import math
import re
from typing import Generic, Sequence, Optional, TypeVar, Any
from fastapi_pagination import Page
from fastapi_pagination.bases import AbstractPage, AbstractParams
from schemas.base_schema import Params
from pydantic.alias_generators import to_camel
from pydantic import BaseModel, ConfigDict, Field

DataType = TypeVar("DataType")
T = TypeVar("T")


def validate_mobile(cls, mobile):
    """
    验证手机号
    """
    pattern = r'^1[3-9]\d{9}$'
    if not re.match(pattern, mobile):
        raise ValidateError(msg="手机格式不正确")
    return mobile


def validate_captcha(cls, captcha):
    """
    验证 验证码
    """
    pattern = r'^\d{4}$'
    if not re.match(pattern, captcha):
        raise ValidateError(msg="验证码格式不正确")
    return captcha


def validate_id_card(cls, id_card):
    """
    验证身份证号码
    """
    pattern = r'^\d{17}[\dXx]$'
    if not re.match(pattern, id_card):
        raise ValidateError(msg="身份证号码格式不正确")
    return id_card


class ResponseBase(BaseModel, Generic[T]):
    code: int = 0
    msg: str = ""
    data: Optional[T]


class ResponsePage(ResponseBase, AbstractPage[T], Generic[T]):
    msg: str = "Success"
    data: Page[T]
    __params_type__ = Params  # Set params related to Page

    @classmethod
    def create(
            cls,
            items: Sequence[T],
            total: int,
            params: AbstractParams,
    ):
        pages = math.ceil(total / params.size)
        return Page(
            items=items,
            page=params.page,
            size=params.size,
            total=total,
            pages=pages
        )


class CacheInfoModel(BaseModel):
    """
    缓存监控对象对应pydantic模型
    """

    model_config = ConfigDict(alias_generator=to_camel)

    cache_key: Optional[str] = Field(default=None, description='缓存键名')
    cache_name: Optional[str] = Field(default=None, description='缓存名称')
    cache_value: Optional[Any] = Field(default=None, description='缓存内容')
    remark: Optional[str] = Field(default=None, description='备注')